package cn.mesmile.juc.reentry;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zb
 * @date 2021/8/16 22:40
 * @Description 可重入锁
 */
public class CanReentryLock {

    public synchronized void add(){
        add();
    }

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();

        new Thread(() -> {
            // 获取锁
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "外层");
                // 外面获取锁之后，这里的锁可以无障碍进入
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "内层");
                }finally {
                    lock.unlock();
                }
            }finally {
                lock.unlock();
            }
        },"t2").start();


        // 递归锁
//        new CanReentryLock().add();

//        Object o = new Object();
//        // 可重入锁
//        new Thread(()->{
//            synchronized (o) {
//                System.out.println(Thread.currentThread().getName() +" 外层");
//                synchronized (o) {
//                    System.out.println(Thread.currentThread().getName() +" 中层");
//                    synchronized (o) {
//                        System.out.println(Thread.currentThread().getName() +" 内层");
//                    }
//                }
//            }
//        },"t1").start();

    }
}
